package com.lingyuting.orm;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.apache.commons.dbutils.DbUtils;

public class DbManager {

    // private static Properties prop;
    public static Connection conn = null;
    private static DbManager instance;

    private DbManager() {
    }

    public static DbManager getInstance() {
        if (null == instance) {
            instance = new DbManager();
        }
        return instance;
    }

    // static {
    // prop = new Properties();
    // InputStream in = Object.class.getResourceAsStream("/db.properties");
    // try {
    // prop.load(in);
    // } catch (IOException e) {
    // throw new RuntimeException(e);
    // }
    // }

    public Connection getConnection() {
        try {
            if (conn != null && !conn.isClosed()) {
                return conn;
            }
        } catch (SQLException e) {
        }
        // String url = prop.getProperty("url");
        // String user = prop.getProperty("user");
        // String password = prop.getProperty("password");

        String url = "jdbc:mysql://127.0.0.1:3306/test?characterEncoding=UTF-8";
        String jdbcDriver = "com.mysql.jdbc.Driver";
        String user = "root";
        String password = "root";
        DbUtils.loadDriver(jdbcDriver);
        try {
            return conn = DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            e.printStackTrace();
            DbUtils.closeQuietly(conn);
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void finalize() {
        DbUtils.closeQuietly(conn);
    }
}
